<template>
  <div class="dashboard">
    <!-- 数据卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-header">
            <span>总用户数</span>
            <el-tag type="success">总计</el-tag>
          </div>
          <div class="card-content">
            <div class="value">{{ statistics.totalUsers }}</div>
            <div class="trend">
              <span>团队成员</span>
              <span class="up">
                {{ statistics.activeUsers}}
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-header">
            <span>总文章数</span>
            <el-tag type="warning">总计</el-tag>
          </div>
          <div class="card-content">
            <div class="value">{{ statistics.totalArticles }}</div>
            <div class="trend">
              <span>今日新增</span>
              <span class="up">
                {{ statistics.newArticlesToday }}
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-header">
            <span>总资源数</span>
            <el-tag type="info">总计</el-tag>
          </div>
          <div class="card-content">
            <div class="value">{{ statistics.totalResources }}</div>
            <div class="trend">
              <span>资源类型</span>
              <span class="up">
                {{ Object.keys(statistics.resourcesByType || {}).length }}
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-header">
            <span>总成就数</span>
            <el-tag type="danger">总计</el-tag>
          </div>
          <div class="card-content">
            <div class="value">{{ statistics.totalAchievements }}</div>
            <div class="trend">
              <span>成就类型</span>
              <span class="up">
                {{ Object.keys(statistics.achievementsByType || {}).length }}
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 快捷导航 -->
<!--    <el-row :gutter="20" class="nav-row">-->
<!--      <el-col :span="3" v-for="(item, index) in navItems" :key="index">-->
<!--        <el-card shadow="hover" class="nav-card" @click="handleNavClick(item)">-->
<!--          <div class="nav-icon">-->
<!--            <el-icon :size="32" :color="item.color">-->
<!--              <component :is="item.icon" />-->
<!--            </el-icon>-->
<!--          </div>-->
<!--          <div class="nav-title">{{ item.title }}</div>-->
<!--        </el-card>-->
<!--      </el-col>-->
<!--    </el-row>-->
    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>文章分类分布</span>
            </div>
          </template>
          <div ref="articlesChart" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>资源类型分布</span>
            </div>
          </template>
          <div ref="resourcesChart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 成果统计图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>成果类型分布</span>
            </div>
          </template>
          <div ref="achievementTypePieChart" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>用户成果量排名</span>
            </div>
          </template>
          <div ref="achievementUserBarChart" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>年级成果量统计</span>
            </div>
          </template>
          <div ref="achievementGradeBarChart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 任务统计图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>用户任务完成平均时间</span>
            </div>
          </template>
          <div ref="tasksAvgTimeChart" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>用户任务完成数量</span>
            </div>
          </template>
          <div ref="tasksUserCompletionChart" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>年级任务完成量</span>
            </div>
          </template>
          <div ref="tasksGradePieChart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import * as echarts from 'echarts'
import {
  User,
  DataAnalysis,
  ShoppingCart,
  List,
  Money,
  Message,
  PriceTag,
  Setting
} from '@element-plus/icons-vue'
import {
  getUserStatistics,
  getArticleStatistics,
  getResourceStatistics,
  getAchievementStatistics,
  getOverviewStatistics,
  getAchievementTypePie,
  getAchievementUserBar,
  getAchievementGradeBar,
  getTasksStatistics,
  getTasksAvgCompletionTime,
  getTasksUserCompletion,
  getTasksGradePie
} from './home'

// 统计数据
const statistics = reactive({
  usersByStatus:0,
  totalUsers: 0,
  activeUsers: 0,
  totalArticles: 0,
  newArticlesToday: 0,
  totalResources: 0,
  resourcesByType: {},
  totalAchievements: 0,
  achievementsByType: {},
  totalTasks: 0,
  completedTasks: 0,
  pendingTasks: 0
})

// 导航项
const navItems = ref([
  { icon: User, title: '用户', color: '#69c0ff' },
  { icon: DataAnalysis, title: '分析', color: '#69c0ff' },
  { icon: ShoppingCart, title: '商品', color: '#ff9c6e' },
  { icon: List, title: '订单', color: '#b37feb' },
  { icon: Money, title: '票据', color: '#ffd666' },
  { icon: Message, title: '消息', color: '#5cdbd3' },
  { icon: PriceTag, title: '标签', color: '#ff85c0' },
  { icon: Setting, title: '配置', color: '#ffc069' }
])

// 图表实例
const articlesChart = ref()
const resourcesChart = ref()
// 成果图表实例
const achievementTypePieChart = ref()
const achievementUserBarChart = ref()
const achievementGradeBarChart = ref()
// 任务图表实例
const tasksAvgTimeChart = ref()
const tasksUserCompletionChart = ref()
const tasksGradePieChart = ref()

// 初始化文章分类分布图表
const initArticlesChart = (data: any) => {
  const chart = echarts.init(articlesChart.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: Object.entries(data.articlesByMenu || {}).map(([key, value]) => ({
          value,
          name: `${key}`
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

// 初始化资源类型分布图表
const initResourcesChart = (data: any) => {
  const chart = echarts.init(resourcesChart.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: Object.entries(data.resourcesByType || {}).map(([key, value]) => ({
          value,
          name: `${key}`
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

// 初始化成果类型饼图
const initAchievementTypePieChart = (data: any) => {
  const chart = echarts.init(achievementTypePieChart.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      type: 'scroll'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: data.data || [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

// 初始化用户成果量柱状图
const initAchievementUserBarChart = (data: any) => {
  const chart = echarts.init(achievementUserBarChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.xAxis || [],
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '成果数量',
        type: 'bar',
        data: data.series || [],
        itemStyle: {
          color: '#91cc75'
        }
      }
    ]
  }
  chart.setOption(option)
}

// 初始化年级成果量柱状图
const initAchievementGradeBarChart = (data: any) => {
  const chart = echarts.init(achievementGradeBarChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.xAxis || [],
      axisLabel: {
        interval: 0
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '成果数量',
        type: 'bar',
        data: data.series || [],
        itemStyle: {
          color: '#5470c6'
        }
      }
    ]
  }
  chart.setOption(option)
}

// 初始化用户任务完成平均时间柱状图
const initTasksAvgTimeChart = (data: any) => {
  const chart = echarts.init(tasksAvgTimeChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c} 小时'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.xAxis || [],
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '小时'
    },
    series: [
      {
        name: '平均完成时间',
        type: 'bar',
        data: data.series || [],
        itemStyle: {
          color: '#ee6666'
        }
      }
    ]
  }
  chart.setOption(option)
}

// 初始化用户任务完成数量柱状图
const initTasksUserCompletionChart = (data: any) => {
  const chart = echarts.init(tasksUserCompletionChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.xAxis || [],
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '完成任务数',
        type: 'bar',
        data: data.series || [],
        itemStyle: {
          color: '#73c0de'
        }
      }
    ]
  }
  chart.setOption(option)
}

// 初始化年级任务完成量饼图
const initTasksGradePieChart = (data: any) => {
  const chart = echarts.init(tasksGradePieChart.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      type: 'scroll'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: data.data || [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const [
      users, 
      articles, 
      resources, 
      achievements, 
      overview,
      achievementTypePie,
      achievementUserBar,
      achievementGradeBar,
      tasksStats,
      tasksAvgTime,
      tasksUserCompletion,
      tasksGradePie
    ] = await Promise.all([
      getUserStatistics(),
      getArticleStatistics(),
      getResourceStatistics(),
      getAchievementStatistics(),
      getOverviewStatistics(),
      getAchievementTypePie(),
      getAchievementUserBar(),
      getAchievementGradeBar(),
      getTasksStatistics(),
      getTasksAvgCompletionTime(),
      getTasksUserCompletion(),
      getTasksGradePie()
    ])

    Object.assign(statistics, {
      totalUsers: users.totalUsers,
      activeUsers: users.activeUsers,
      totalArticles: articles.totalArticles,
      newArticlesToday: overview.newArticlesToday,
      totalResources: resources.totalResources,
      resourcesByType: resources.resourcesByType,
      totalAchievements: achievements.totalAchievements,
      achievementsByType: achievements.achievementsByType,
      totalTasks: tasksStats.totalTasks,
      completedTasks: tasksStats.completedTasks,
      pendingTasks: tasksStats.pendingTasks
    })

    // 初始化所有图表
    initArticlesChart(articles)
    initResourcesChart(resources)
    initAchievementTypePieChart(achievementTypePie)
    initAchievementUserBarChart(achievementUserBar)
    initAchievementGradeBarChart(achievementGradeBar)
    initTasksAvgTimeChart(tasksAvgTime)
    initTasksUserCompletionChart(tasksUserCompletion)
    initTasksGradePieChart(tasksGradePie)
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 处理导航点击
const handleNavClick = (item: any) => {
  console.log('点击了导航项:', item.title)
}

onMounted(() => {
  fetchStatistics()
  
  // 监听窗口大小变化，重新渲染图表
  window.addEventListener('resize', () => {
    const charts = [
      articlesChart.value, 
      resourcesChart.value,
      achievementTypePieChart.value,
      achievementUserBarChart.value,
      achievementGradeBarChart.value,
      tasksAvgTimeChart.value,
      tasksUserCompletionChart.value,
      tasksGradePieChart.value
    ]
    
    charts.forEach(chart => {
      if (chart) {
        echarts.getInstanceByDom(chart)?.resize()
      }
    })
  })
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.data-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.card-content {
  text-align: center;
}

.value {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
}

.trend {
  font-size: 14px;
  color: #666;
}

.trend .up {
  color: #67c23a;
}

.trend .down {
  color: #f56c6c;
}

.chart-row {
  margin-top: 20px;
}

.nav-row {
  margin-top: 20px;
}

.nav-card {
  cursor: pointer;
  text-align: center;
  padding: 10px 0;
}

.nav-icon {
  margin-bottom: 10px;
}

.nav-title {
  font-size: 14px;
  color: #666;
}
</style>
